/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jb.repair.hardware.nfc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jb.repair.R;
import com.jb.repair.acticity.CheckRegisActivity;
import com.jb.repair.common.AppConfig;
import com.jb.repair.dao.Db;

import java.util.List;

/**
 * An {@link Activity} which handles a broadcast of a new tag that the device
 * just discovered.
 */
public class TagViewerActivity extends Activity {

    static final String TAG = "ViewTag";

    /**
     * This activity will finish itself in this amount of time if the user
     * doesn't do anything.
     */
    static final int ACTIVITY_TIMEOUT_MS = 1 * 1000;

    public static boolean NOW_IN_PROPER_PAGE = false; // 是否在点检位置页面上

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e("TagViewerActivity","发现标签");
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_tag_viewer);

        // 仅在点检位置页面扫码时进行响应，否则不响应
        if (NOW_IN_PROPER_PAGE) {
            resolveIntent(getIntent());
        } else {
            finish();
        }
    }

    void resolveIntent(Intent intent) {
        // Parse the intent
        String action = intent.getAction();
//        Log.e("Tag",action);

        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
            byte[] bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);

            String tagId = bytesToHexString(bytesId);//将其转换成字符串格式

            Log.i("tagId:-----------", tagId);

            boolean exist = false;
            Cursor cursor = Db.getInstance(TagViewerActivity.this).getCursor("Select nfc_ID from TB_SI_PLACE");

            while (cursor.moveToNext()) {
                String tag = cursor.getString(cursor.getColumnIndex("nfc_ID"));
                String tag1 = tag.replaceAll(":", "");
//                Log.i("tagId1:", tag1);
                if (tagId.equals(tag1)) {
                    exist = true;

                    Intent intent1 = new Intent(TagViewerActivity.this, CheckRegisActivity.class);
                    String sql = "select place_id from TB_SI_PLACE where nfc_id = '" + tag + "'";
                    SQLiteDatabase db = getApplicationContext().openOrCreateDatabase(AppConfig.DB_PATh, Context.MODE_PRIVATE, null);
                    Cursor c = db.rawQuery(sql, null);
                    String local = "";
                    if (c.moveToFirst())
                        local = c.getString(0);
                    c.close();
                    db.close();
                    intent1.putExtra("posId", local);

                    // 添加硬件扫码进入标志
                    intent1.putExtra("jumpFromTag", true);
                    Log.i(TAG,"添加硬件扫码进入标志");
                    CheckRegisActivity.changable = true;

                    startActivity(intent1);
                    finish();
                }
            }

            if (!exist) {
                Toast.makeText(TagViewerActivity.this, "此位置不属于此任务", Toast.LENGTH_SHORT).show();
                finish();
            }

        } else {
            finish();
            return;
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        setIntent(intent);
        resolveIntent(intent);
    }

    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp);
        }
        return sb.toString();
    }
}
